import './list.css';
import React, { Component } from 'react'

class List extends Component {
  constructor(props) {
    super(props)
    this.state = {
      //可视区域高度
      screenHeight:0,
      //偏移量
      startOffset:0,
      //起始索引
      start:0,
      //结束索引
      end:null,
    }

    this.$el = React.createRef()

    this.scrollEvent = this.scrollEvent.bind(this)
  }

  //列表总高度
  get listHeight(){
    return this.props.listData.length * this.props.itemSize;
  }
  //可显示的列表项数
  get visibleCount(){
    return Math.ceil(this.state.screenHeight / this.props.itemSize)
  }
  //偏移量对应的style
  get getTransform(){
    return `translate3d(0,${this.state.startOffset}px,0)`;
  }
  //获取真实显示列表数据
  get visibleData(){
    return this.props.listData.slice(this.state.start, Math.min(this.state.end,this.props.listData.length));
  }

  componentDidMount() {
    this.setState({
      screenHeight: this.$el.current.clientHeight,
    }, () => {
      this.setState({
        start: 0,
        end: this.visibleCount,
      })
    })
  }

  render() {
    const {
      itemSize,
    } = this.props

    const {
      listHeight,
      visibleData,
    } = this

    return (
      <div className="infinite-list-container" ref={this.$el} onScroll={this.scrollEvent}>
        <div className="infinite-list-phantom" style={{ height: listHeight + 'px' }}></div>
        <div className="infinite-list" ref={this.list} style={{ transform: this.getTransform }}>
          {
            visibleData.map((item, index) =>
              <div className='infinite-list-item' key={index}
                style={{ height: itemSize + 'px' }}
              >{ item }</div>
            )
          }
        </div>
      </div>
    );
  }

  scrollEvent() {
    //当前滚动位置
    let scrollTop = this.$el.current.scrollTop
    const start = Math.floor(scrollTop / this.props.itemSize)
    this.setState({
      //此时的开始索引
      start: start,
      //此时的结束索引
      end: start + this.visibleCount,
      startOffset: scrollTop - (scrollTop % this.props.itemSize),
    })
  }
}

export default List;
